<template>
    <el-form :inline="true" :model="formData" class="demo-form-inline">


        <el-form-item label="单据编号">
            <el-input v-model="formData.billNo" placeholder="自动生成单据编号" readonly></el-input>
        </el-form-item>

        <el-form-item label="创建时间">
            <el-date-picker type="datetime" placeholder="选择日期与时间" clearable class="input" />
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="submitForm">保存</el-button>
        </el-form-item>

        <el-form-item label="财务人员：">
            <el-select v-model="formData.erpPerson.perName" clearable style="width: 200px; margin-left: 10px;"
                placeholder="请选择财务人员">
                <el-option v-for="persons in person" :key="persons.perId" :label="persons.perName"
                    :value="persons.perId" />
                <el-option :value="undefined" disabled style="cursor: pointer">
                    <el-button type="text" v-perm:finance:revenue:insert:financestaff="insert">
                        <i class="el-icon-menu"></i>新增财务人员
                    </el-button>
                </el-option>
            </el-select>
        </el-form-item>
        <el-button type="primary" @click="addRow" class="ant-btn ant-btn-primary">
            <el-icon class="el-icon-left">
                <Plus />
            </el-icon>
            <span>插入行</span>
        </el-button>
        <el-table :data="tableData" show-summary style="width: 100%">
            <el-table-column v-if="showIdColumn" label="id" width="400">
                <template #default="{ row }">
                    <el-input v-model="row.id"></el-input>
                </template>
            </el-table-column>
            <el-table-column label="账户名称" width="400">
                <template #default="{ row }">
                    <el-select clearable style="width: 200px;" placeholder="请选择账户" v-model="row.zh">
                        <el-option v-for="account in accounts" :key="account.id" :label="account.name"
                            :value="account.accId" />
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column label="金额" width="400">
                <template #default="{ row }">
                    <el-input v-model="row.je" placeholder="请输入金额"></el-input>
                </template>
            </el-table-column>
            <el-table-column label="备注" width="400">
                <template #default="{ row }">
                    <el-input v-model="row.bz" placeholder="请输入备注"></el-input>
                </template>
            </el-table-column>

        </el-table>


        <div class="index-body zb">
            <el-form-item label="付款账户：" style="margin-right: 120px;">
                <el-select clearable style="width: 200px;" placeholder="请选择账户" v-model="formData.erpAccount.accId">
                    <el-option v-for="account in accounts" :key="account.id" :label="account.name"
                        :value="account.accId" />
                </el-select>
            </el-form-item>

            <el-form-item label="实付金额：" style="margin-right: 100px;" v-model="totalReceived">
                <el-input style="width: 240px" :value="totalReceived" readonly></el-input>
            </el-form-item>




        </div>

        <div class="ant-coloery" style="margin-right: 10px;">
            <el-form-item label="附件：">
                <el-button plain>
                    <el-icon style="margin-right: 10px;">
                        <MessageBox />
                    </el-icon>上传附件
                </el-button>
            </el-form-item>
        </div>
    </el-form>

    <el-dialog :destroy-on-close="true" :title="title" v-model="visible" width="80%"
        style="margin-left: 250px; margin-top: 200px">
        <router-view @close="close" :data="data" :supId="ruleForm.supId"></router-view>
    </el-dialog>
</template>

<script  setup>
import { reactive, ref, onMounted, defineProps } from 'vue';
import router from '@/router';
import request from '@/api/request';
import { ElMessage } from 'element-plus';
import { computed } from 'vue';
let props = defineProps(["data"]);
let formData = ref({ ...props.data });
console.log(formData.value);

// 计算实际收款总和
// 计算实际收款总和
const totalReceived = computed(() => {
    return tableData.value.reduce((sum, row) => sum + (parseFloat(row.je) || 0), 0);
});

// 定义优惠金额的响应式变量
const discountAmount = ref(0); // 用于存储优惠金额

const actualReceived = computed(() => {
    const total = totalReceived.value; // 使用合计收款计算
    return total - discountAmount.value; // 减去优惠金额
});


const visible = ref(false);
const title = ref("");
const data = ref({});
const ruleForm = ref({
    supId: '',
    linkNumber: '',
    number: '',
    organId: '',
    accountId: '',
    handsPersonId: '',
    discountAmount: '',
    actualReceived: ''
});

const close = () => {
    visible.value = false;
};

const tableData = ref([{ barCode: '', categoryName: '', color: '' }]);

const addRow = () => {
    tableData.value.push({
        barCode: '',
        categoryName: '',
        color: '',
    });
};
const show = ref([]);
const loadCushowstomers = () => {
    request({
        url: '/basic/vendor/list2',
        method: 'get',
        params: {
            subType: '2'
        }

    }).then(res => {

        show.value = res.data; // 更新客户数据
    }).catch(err => {
        console.error(err);
    });
};
// const ids = formData.value.erpAccountItems.map(item => item.id);

loadCushowstomers();
const accounts = ref([]);
const loadAccounts = () => {
    request({ url: '/basic/account/list', method: 'get' })
        .then(res => accounts.value = res.data)
        .catch(err => console.error(err));
};
loadAccounts();
const submitForm = () => {
    const totalAmount = tableData.value.reduce((sum, row) => sum + (parseFloat(row.je) || 0), 0);

 
    const data = {
        erpAccountHead: {
            billNo: formData.value.billNo,
            creator: '1',
            accountId: formData.value.accId,
            changeAmount: -totalReceived.value, 
            totalPrice: -totalReceived.value,
            status: '0',
        },
        erpAccountItems: tableData.value.map(row => ({
            id:row.id,
            remark: row.bz || '',
            eachAmount: -row.je,
            finishDebt: row.qk, 
            accountId: row.zh
        })),
    };
    console.log(tableData.value)
    console.log(data)
    // 发送请求
    request({
        url: '/accountHead/update',
        method: 'put',
        params: {billNo: formData.value.billNo
        },

        data: data,
        headers: { 'Content-Type': 'application/json' },
    }).then(res => {
        console.log(res);
        ElMessage.success('提交成功');
    }).catch(err => {
        console.error(err);
        ElMessage.error('提交失败: ' + (err.message || '请稍后重试'));
    });
};




onMounted(() => {
    console.log(formData.value.erpAccountItems)
        tableData.value = formData.value.erpAccountItems.map(item => ({
            id:item.id,
            number: item.number ,
            je: Math.abs(item.eachAmount) || 0,
            bz: item.bremark || '',
            qk: Math.abs(item.needDebt)||0-Math.abs(item.finishDebt) || 0,
           sk: item.eachAmount || 0,
           zh: item.accountId,
        }));
    
});




const customers = ref([]); // 存储客户数据  

const loadCustomers = () => {
    request({ url: '/basic/vendor/findBy', method: 'get' })
        .then(res => {
            console.log(res);
            customers.value = res.data; // 更新客户数据  
        }).catch(err => {
            console.error(err);
        });
};
loadCustomers();

const person = ref({});
const personfin = () => {
    request({ url: '/basic/person/list', method: 'get' })
        .then(res => {
            person.value = res.data;
            console.log(res);
        });
}
personfin();

const insert = (p) => {
    title.value = p.cname;
    visible.value = true;
    router.push(p.path);
    personfin();
};

// 页面加载时生成订单编号  
onMounted(() => {
    let currentOrderNumber = parseInt(localStorage.getItem('orderNumber') || '1', 10);
    currentOrderNumber++;
    const formattedOrderNumber = currentOrderNumber.toString().padStart(10, '0');
    ruleForm.value.number = formattedOrderNumber;
    localStorage.setItem('orderNumber', currentOrderNumber.toString());
});
</script>

<style>
.demo-form-inline .el-input {
    --el-input-width: 220px;
}

.demo-form-inline .el-select {
    --el-select-width: 220px;
}
</style>